package com.gsc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.gsc.constants.SystemConstants;
import com.gsc.domain.ResponseResult;
import com.gsc.domain.dto.AddArticleDto;
import com.gsc.domain.dto.ArticleListDto;
import com.gsc.domain.entity.Article;
import com.gsc.domain.entity.ArticleTag;
import com.gsc.domain.entity.Category;
import com.gsc.domain.entity.Tag;
import com.gsc.domain.vo.ArticleDateVo;
import com.gsc.domain.vo.ArticleListVo;
import com.gsc.domain.vo.HotArticleVo;
import com.gsc.domain.vo.PageVo;
import com.gsc.mapper.ArticleMapper;
import com.gsc.service.ArticleService;
import com.gsc.service.ArticleTagService;
import com.gsc.service.CategoryService;
import com.gsc.utils.BeanCopyUtils;
import com.gsc.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author gscstart
 * @create 2023/1/14-9:04
 *
 *
 */
@Service
@Transactional
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleTagService articleTagService;

    @Autowired
    private ArticleMapper articleMapper;

    /**
     * 查询热门文章列表
     * @return List<HotArticleVo>
     */
    @Override
    public ResponseResult hotArticleList() {
        //查询热门文章，封装成ResponseResult返回
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //必须是正式文章,比较文章的状态
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        //按照浏览量进行排序
        queryWrapper.orderByDesc(Article::getViewCount);
        //最多只查询10条
        Page<Article> page = new Page(1,10);
        page(page,queryWrapper);
        //获取集合数据
        List<Article> records = page.getRecords();
        //封装vo返回
        List<HotArticleVo> vos = BeanCopyUtils.copyBeanList(records, HotArticleVo.class);
        return ResponseResult.okResult(vos);
    }

    /**
     * 页分页文章展示 和 分类的文章展示
     * @param pageNum 起始页
     * @param pageSize 每页大小
     * @param categoryId 分类id
     * @return PageVo
     */
    @Override
    public ResponseResult articleList(Integer pageNum, Integer pageSize, Long categoryId) {

        //查询条件：
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //如果传categoryId，查询时就要和传入的相同
        //如果传过来的id不为空且大于0，就执行
        queryWrapper.eq(Objects.nonNull(categoryId)&&categoryId>0,Article::getCategoryId,categoryId);
        //如果没传不用判断
        //状态是正式发布的
        queryWrapper.eq(Article::getStatus,SystemConstants.ARTICLE_STATUS_NORMAL);
        //对isTop进行降序
        queryWrapper.orderByDesc(Article::getIsTop);

        //分页查询
        Page<Article> page = new Page<>(pageNum,pageSize);
        page(page,queryWrapper);

        //将分类名查询出来，通过categoryId
        List<Article> articles = page.getRecords();

        //通过分类id，在分类表中查询分类名(lambda表达式)，将其赋值给文章表中的分类名字段
        articles.stream()
                .map(article -> article.setCategoryName(categoryService.getById(article.getCategoryId()).getName()))
                .collect(Collectors.toList());

        //封装查询结果
        List < ArticleListVo > articleListVos = BeanCopyUtils.copyBeanList(page.getRecords(), ArticleListVo.class);
        PageVo pageVo = new PageVo(articleListVos, page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    /**
     * 根据文章id，查询文章内容详情
     * @param id 文章id
     * @return ArticleDateVo
     */
    @Override
    public ResponseResult getArticleDetail(Long id) {
        //根据id查询文章
        Article article = this.getById(id);
        //从redis中获取viewCount :这里要判断一下redis是否存在
        Integer viewCount = redisCache.getCacheMapValue(SystemConstants.REDIS_VIEW_COUNT, id.toString());
        article.setViewCount(viewCount.longValue());
        //转换成vo
        ArticleDateVo articleDateVo = BeanCopyUtils.copyBean(article, ArticleDateVo.class);
        //根据分类id查询分类名
        Long categoryId = articleDateVo.getCategoryId();
        Category category = categoryService.getById(categoryId);
        //判断一下是否查到数据，可以避免空指针异常
        if(category != null){
            articleDateVo.setCategoryName(category.getName());
        }
        //封装响应 返回
        return ResponseResult.okResult(articleDateVo);
    }

    /**
     * 更新文章浏览量业务
     * @param id
     * @return
     */
    @Override
    public ResponseResult updateViewCount(Long id) {
        //更新redis中对应 id的浏览量
        redisCache.incrementCacheMapValue(SystemConstants.REDIS_VIEW_COUNT,id.toString(),1);
        return ResponseResult.okResult();
    }

    @Override
    @Transactional
    public ResponseResult add(AddArticleDto articleDto) {

        //添加 博客
        Article article = BeanCopyUtils.copyBean(articleDto, Article.class);
        save(article);

        List<ArticleTag> articleTags = articleDto.getTags().stream()
                .map(tagId -> new ArticleTag(article.getId(), tagId))
                .collect(Collectors.toList());

        //添加 博客和标签的关联
        articleTagService.saveBatch(articleTags);

        return ResponseResult.okResult();
    }

    @Override
    @Transactional
    public ResponseResult articleLists(ArticleListDto articleListDto) {
        /*
                //分页
        PageHelper.startPage(articleListDto.getPageNum(),articleListDto.getPageSize());
        //查询所有文章数据，根据标题和摘要进行模糊查询
        List<Article> articleLists = articleMapper.articleLists(articleListDto);
        PageVo pageVo = new PageVo(articleLists, Long.valueOf(articleLists.size()));
        return ResponseResult.okResult(pageVo);
         */
        //分页
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(articleListDto.getTitle()),Article::getTitle,articleListDto.getTitle());
        queryWrapper.like(StringUtils.hasText(articleListDto.getSummary()),Article::getSummary,articleListDto.getSummary());

        Page<Article> articlePage = new Page<>(articleListDto.getPageNum(),articleListDto.getPageSize());
        page(articlePage,queryWrapper);
        PageVo pageVo = new PageVo(articlePage.getRecords(), articlePage.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult selectArticleById(Long id) {
        //根据id查询文章信息
        Article article = articleMapper.selectById(id);
        AddArticleDto addArticleDto = BeanCopyUtils.copyBean(article, AddArticleDto.class);

        //查询文章所对应的标签
        LambdaQueryWrapper<ArticleTag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArticleTag::getArticleId,id);
        BaseMapper<ArticleTag> articleTagMapper = articleTagService.getBaseMapper();
        List<ArticleTag> articleTags = articleTagMapper.selectList(queryWrapper);
        List<Long> tagIds = articleTags.stream()
                .map(articleTag -> articleTag.getTagId())
                .collect(Collectors.toList());

        addArticleDto.setTags(tagIds);
        //封装数据返回
        return ResponseResult.okResult(addArticleDto);
    }

    @Override
    @Transactional
    public ResponseResult updateArticle(AddArticleDto addArticleDto, Long id) {

        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getId,addArticleDto.getId());
        Article article = BeanCopyUtils.copyBean(addArticleDto, Article.class);
        //更新文章
        articleMapper.update(article,queryWrapper);
        //更新标签
            //删除原有的 标签和博客的关联
        LambdaQueryWrapper<ArticleTag> articleTagLambdaQueryWrapper = new LambdaQueryWrapper<>();
        articleTagLambdaQueryWrapper.eq(ArticleTag::getArticleId,article.getId());
        articleTagService.remove(articleTagLambdaQueryWrapper);

        List<ArticleTag> articleTags = addArticleDto.getTags().stream()
                .map(tagId -> new ArticleTag(article.getId(), tagId))
                .collect(Collectors.toList());
        articleTagService.saveBatch(articleTags);

        //返回响应
        return ResponseResult.okResult();
    }
}
